package com.android.accessibility.utils;

import java.util.HashMap;

import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;

import com.android.accessibility.R;
import com.android.accessibility.base.BaseFragment;

public class HomePageSwitchHelper {

    private FragmentActivity mActivity;
    private HashMap<String, BaseFragment> mHashMap;
    private BaseFragment mCurrentFragment;

    public HomePageSwitchHelper(FragmentActivity activity) {
        mActivity = activity;
        mHashMap = new HashMap<String, BaseFragment>();
    }

    public void switchFragment(String tag, BaseFragment fragment) {
        replaceFragment(tag, fragment);
    }

    public BaseFragment getCurrentFragment() {
        return mCurrentFragment;
    }

    private BaseFragment getFragmentFromHash(String tag) {
        if (mHashMap == null) {
            mHashMap = new HashMap<String, BaseFragment>();
        }
        if (mHashMap.containsKey(tag)) {
            return mHashMap.get(tag);
        }
        return null;
    }

    private void putFragmentToHash(String tag, BaseFragment fragment) {
        if (mHashMap == null) {
            mHashMap = new HashMap<String, BaseFragment>();
        }
        if (!mHashMap.containsKey(tag)) {
            mHashMap.put(tag, fragment);
        }
    }

    private void replaceFragment(String tag, BaseFragment fragment) {
        try {
            if (fragment != null) {
                BaseFragment f = getFragmentFromHash(tag);
                if (mCurrentFragment == fragment) {
                    return;
                }

                if (mActivity == null) {
                    return;
                }

                FragmentTransaction transaction = mActivity
                        .getSupportFragmentManager().beginTransaction();

                if (f == null) {
                    transaction.add(R.id.content, fragment);
                    putFragmentToHash(tag, fragment);
                }
                if (mCurrentFragment != null) {
                    transaction.hide(mCurrentFragment);
                }
                transaction.show(fragment);
                transaction.commitAllowingStateLoss();
                mCurrentFragment = fragment;
            }
        } catch (Exception e) {
            Log.d(Log.TAG, "error : " + e);
        }
    }
}
